package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.util.concurrent.TimeUnit;

import static com.sky.constant.RedisConstant.ADMIN_TOKEN;

@Component
@Slf4j
@RequiredArgsConstructor
public class RedisTokenTime implements HandlerInterceptor {

    private final StringRedisTemplate redisTemplate;

    private final JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取Redis中的token
        String token = redisTemplate.opsForValue().get(ADMIN_TOKEN);
        if (token == null) {
            log.info("Token不存在，请重新登录");
            response.setStatus(401);
            return false;
        }
        //解析token
        try {
//            log.info("Redis--jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            //刷新token的有效期
            redisTemplate.expire(ADMIN_TOKEN, jwtProperties.getAdminTtl(), TimeUnit.SECONDS);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
//            log.info("当前员工id：{}", empId);
            //存入用户id
            BaseContext.setCurrentId(empId);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除用户id
        BaseContext.removeCurrentId();
    }
}
